﻿using Dapper;
using Entity;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
using ServiceCore;
using ServiceCore.Tool;
using ServiceCore.Tool.JD_Pay;
using ServiceCore.Tool.Mqtt;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Customer.Bussiness_Service
{

    public interface Irk_tool_service
    {
        /// <summary>
        /// 销售开通账号
        /// </summary>
        /// <param name="user"></param>
        /// <param name="Sms"></param>
        /// <param name="roleid"></param>
        ResultModel SaleOnly_Register(Entity.User user, string Sms, string roleid = "");
        /// <summary>
        /// 开通账号
        /// </summary>
        /// <param name="user"></param>
        /// <param name="Sms"></param>
        /// <param name="roleid"></param>
        /// <returns></returns>
        ResultModel Register(Entity.User user, string Sms, string roleid = "");
        /// <summary>
        /// 获取机器
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultListModel<MchByBatch> getMchs(getMchs_params query);
        /// <summary>
        /// 添加机器
        /// </summary>
        /// <param name="model"></param>
        /// <param name="slots"></param>
        /// <returns></returns>
        ResultObjModel Create(Entity.Mch model, List<Entity.Slot> slots);
        /// <summary>
        /// 编辑机器信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        ResultModel Edit(Entity.Mch model);
        /// <summary>
        /// 获取simboss卡列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        SimListPageObjList get_simreg_list(Base_PageList_Params query);
        ResultObjModel queryMerchantsSettle(string queryStartTime, string queryEndTime, string merchantNo = "", string orderStatus = "", int pageNum = 1, int pageSize = 50);
        ResultObjExtModel queryApplySingle(string merchantNo);
        ResultObjModel queryMerchantWXNo(string merchantNo = "");
        /// <summary>
        ///
        /// </summary>
        /// <param name="order_id"></param>
        /// <param name="baseuserid"></param>
        /// <returns></returns>
        ResultObjModel querytrade(string order_id, string baseuserid);
        ResultObjModel ReApplySingle(string merchantNo, string productid, string mfee = "0.6");
        /// <summary>
        /// 
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultObjModel search_order_model(order_search_pagelist_Params query);
        /// <summary>
        /// 获取机器列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultListModel<get_mch_pagelist_result> get_mch_pagelist(tool_get_mch_pagelist_query query);
        /// <summary>
        /// 分配用户
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="mchid"></param>
        /// <returns></returns>
        ResultModel distribution_user(string userid, string mchid);
        /// <summary>
        ///  编辑机器
        /// </summary>
        /// <param name="save_params"></param>
        /// <returns></returns>
        ResultObjModel NewEditMch(EditMch save_params);
        ResultObjModel get_user_merchantNo(string baseuserid);

        /// <summary>
        /// 查询机器详情
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        ResultObjModel search_mch(string keyword);
        /// <summary>
        /// 获取转账信息
        /// </summary>
        /// <param name="month"></param>
        /// <param name="merchantNo"></param>
        /// <param name="orderStatus"></param>
        /// <returns></returns>
        ResultObjExtModel get_jd_result(get_jd_result_params query);

        /// <summary>
        /// 根据京东商户号获取用户信息
        /// </summary>
        /// <param name="merchantNo"></param>
        /// <returns></returns>
        ResultObjModel get_rk_user_forJd(string merchantNo);
        /// <summary>
        ///  修改用户费率为Q6
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        ResultModel rk_user_to_q6(string id);

        ResultObjModel start_rk_for_20200730();
        /// <summary>
        /// 查询京东退款订单
        /// </summary>
        /// <param name="outRefundNo"></param>
        /// <returns></returns>
        ResultObjModel queryrefund(string outRefundNo);

        ResultModel start_clear_run();

        ResultListModel<search_version_model> get_temp_list(search_temp_info query);
        /// <summary>
        /// 处理温度信息
        /// </summary>
        /// <param name="mchid"></param>
        /// <returns></returns>
        ResultModel end_temp(string mchid);
        /// <summary>
        /// 指定处理人
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        ResultModel designated_person(designated_person_params Params);


        ResultModel change_state(string mchid, string diy_remark, int state);
         
    }



    public static class GetNoByTimeStamp
    {

        static object _lock = new object();
        static int count = 1;

        public static string Get()
        {
            lock (_lock)
            {
                if (count >= 100)
                {
                    count = 1;
                }
                Random ran = new Random();
                var number = DateTime.Now.Ticks.ToString().Substring(0, 11) + count.ToString("00") + ran.Next(100, 999);
                count++;
                return number;
            }
        }
    }
    //用于处理售后常用的工具项
    public class rk_tool_service : Irk_tool_service
    {
        private readonly IToole_DI _tool;
        private readonly IJD_API _jdapi;
        private readonly IConfiguration _configuration;
        private readonly IRK_Mqtt _rkMqtt;
        public rk_tool_service(IToole_DI Tool, IJD_API Jdapi, IConfiguration Configuration, IRK_Mqtt RkMqtt)
        {
            _tool = Tool;
            _jdapi = Jdapi;
            _configuration = Configuration;
            _rkMqtt = RkMqtt;
        }

        public int get_return_pool_time_set
        {
            get
            {
                try
                {
                    return Convert.ToInt32(_tool.di_appSettingConfig["user_config:return_pool_time"]);
                }
                catch
                {
                    return 365;
                }
            }
        }
        #region 1 开通账号 
        public ResultModel SaleOnly_Register(Entity.User user, string Sms, string roleid = "")
        {
            return CoreStartDo.ResultAction<ResultModel>(result => {
                if (_tool.di_user.USER.role_id != "Sale" && _tool.di_user.USER.role_id != "Sales_Manager" && _tool.di_user.USER.role_id != "Finance_Manager")
                {
                    result.code = 1;
                    result.msg = "您不是销售人员";
                    return result;
                }
                if (!user.source.HasValue)
                {
                    result.code = 1;
                    result.msg = "必须选择客户来源";
                    return result;
                }
                user.sale_uid = _tool.di_user.USER.uid;
                user.sale_name = _tool.di_user.USER.u_name;
                user.collection_time = DateTime.Now;
                user.return_pool_time = DateTime.Now.AddDays(get_return_pool_time_set);
                return Register(user, Sms, roleid);
            });
        }
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="user"></param>
        /// <param name="Sms"></param>
        /// <param name="roleid"></param>
        /// <returns></returns>
        public ResultModel Register(Entity.User user, string Sms, string roleid = "")
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (!Validate(user.Tel, Sms))
                {
                    result.code = 1;
                    result.msg = "验证码错误";
                    return result;
                }
                else if (IsExistUserName(user.UserName))
                {
                    result.code = 1;
                    result.msg = "用户名已注册";
                    return result;
                }
                else
                {
                    SetCreateModel(user);
                    user.BaseUserId = user.Id = GenerateId();
                    user.Pwd = SecurityToMd5.Run(user.Pwd);  //Common.Encrypt.MD5.MD5Encrypt32(user.Pwd);
                    user.UserStateId = UserState.正常;
                    user.Rate = 0.99m;
                    user.Secret = Guid.NewGuid().ToString().Replace("-", ""); //
                    user.sale_uid = _tool.di_user.USER.uid;
                    user.sale_name = _tool.di_user.USER.u_name;
                    user.collection_time = DateTime.Now;
                    user.return_pool_time = DateTime.Now.AddDays(get_return_pool_time_set);
                    if (Register(user, roleid))
                    {
                        ToVoid(user.Tel, Sms);
                        result.code = 0;
                        result.msg = user.UserName;
                        return result;
                    }
                    result.code = 1;
                    result.msg = "注册失败";
                    return result;
                }
            });
        }
        private void SetCreateModel(Entity.BaseEnity model, bool HasAuth = true)
        {
            if (model == null)
            {
                return;
            }
            model.Id = Guid.NewGuid().ToString();
            model.IsDelete = false;
            model.UpdateOn = model.CreateOn = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); ;

            if (HasAuth)
            {
                if (_tool.di_user.USER != null)
                {
                    model.UpdateBy = model.CreateBy = _tool.di_user.USER.uid;
                }
            }
        }
        private bool Validate(string Tel, string Code)
        {
            string sql = $"select*from dbo.[SMS] where code='{Code}' and  tel='{Tel}' and  IsUsed='false' and ExpireOn>='{System.DateTime.Now.ToString("yyy-MM-dd HH:mm:ss")}' order by createon desc";
            return _tool.di_db.Get_rk_List<Entity.SMS>(sql, null).FirstOrDefault() != null;
        }
        private bool IsExistUserName(string UserName)
        {

            string sql = $"Select count(*)from dbo.[user] where username='{UserName}'";
            return _tool.di_db.Get_rk_List<int>(sql, null).FirstOrDefault() > 0;
        }
        private string GenerateId()
        {
            string sql = "select max(id) from dbo.[user] where len(id)>=4 and len(id)<=6";
            var item = _tool.di_db.Get_rk_List<string>(sql, null).FirstOrDefault();
            if (item != null)
            {
                return (Convert.ToInt32(item) + 1).ToString();
            }
            return "10000";
        }
        private bool Register(User user, string rid = "")
        {

            string roleid = "1";
            if (!string.IsNullOrEmpty(rid))
            {
                user.UserTypeId = UserType.自定义用户;
                roleid = rid;
            }
            else
            {
                switch (user.UserTypeId)
                {
                    case UserType.个人用户:
                        roleid = "1";
                        break;
                    case UserType.企业用户:
                        roleid = "2";
                        break;
                    default:
                        break;
                }
            }
            //添加角色
            string sql = $"insert into [dbo].[UserRoles](USER_ID,ROLE_ID)values('{user.Id}','{roleid}')";
            _tool.di_db.do_rk_Execute(sql, null);
            return _tool.di_db.do_rk_Execute(_tool.di_db.AddBySqlStr<User>(), user) > 0;
        }
        private void ToVoid(string Tel, string Code)
        {
            try
            {
                string dtnow = System.DateTime.Now.ToString("yyy-MM-dd HH:mm:ss");
                var NeedVoid = _tool.di_db.Get_rk_List<SMS>("select top 1 * from SMS where Code=@Code  and Tel=@Tel and ExpireOn<@dtnow", new { Code, Tel, dtnow }).FirstOrDefault();
                if (NeedVoid != null)
                {
                    _tool.di_db.do_rk_Execute("update SMS set IsUsed=@IsUsed where Id=@Id", new { NeedVoid.Id, IsUsed = true });
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
        #region 2 所有机器管理 
        public ResultListModel<MchByBatch> getMchs(getMchs_params query)
        {
            return CoreStartDo.ResultAction<ResultListModel<MchByBatch>>(result =>
            {
                string where = " where  a.isdelete=0 ";
                if (query.updateSearch.HasValue)
                {
                    if (query.updateSearch.Value)
                    {
                        where += string.Format($" and a.app_updateState>=10");
                    }
                    else
                    {
                        where += string.Format($" and a.app_updateState=0");
                    }
                }
                if (!string.IsNullOrWhiteSpace(query.baseuserid))
                {
                    where += string.Format($" and a.baseuserid='{query.baseuserid}'");
                }
                if (query.mchrole != null)
                {
                    string mchinfo = "(";
                    foreach (var item in query.mchrole.mchids)
                    {
                        mchinfo += $"'{item}',";
                    }
                    if (mchinfo != "(")
                    {
                        mchinfo = mchinfo.TrimEnd(',');
                    }
                    mchinfo += ")";
                    where += $" and a.id in {mchinfo}";
                }
                if (!string.IsNullOrWhiteSpace(query.id))
                {
                    where += string.Format($" and a.id like '%{query.id}%'");
                }
                if (!string.IsNullOrWhiteSpace(query.number))
                {
                    where += string.Format($" and a.number like '{query.number}'");
                }
                if (!string.IsNullOrWhiteSpace(query.name))
                {
                    where += string.Format($" and a.name like '%{query.name}%'");
                }
                if (!string.IsNullOrWhiteSpace(query.sn))
                {
                    where += string.Format($" and a.sn like '%{query.sn}%'");
                }
                if (!string.IsNullOrWhiteSpace(query.groupid))
                {
                    if (query.groupid == "0")  //0表示未分组
                    {
                        where += string.Format($" and a.groupid is NULL ");
                    }
                    else
                    {
                        where += string.Format($" and a.groupid='{query.groupid}'");
                    }
                }
                if (query.usetype != null)
                {
                    where += string.Format(" and a.ad_type='{0}'", (int)query.usetype);
                }
                if (!string.IsNullOrWhiteSpace(query.username))
                {

                    where += string.Format(" and u.username='{0}'", query.username);
                }
                string sql = string.Format($@"select  c.name as groupname,d.name as statename,a.* ,u.username,batch.Batch_No,batch.MchModel,batch.Remark as BatchRemark  from mch  a 
                                        left join dbo.[mchgroup] c on a.groupid=c.id 
                                        left join dic  d  on a.[state]=d.id  left join dbo.[User] u on a.baseuserid=u.Id
                                        left join Mch_Batch batch on batch.BatchID = a.BatchID ");

                var data = _tool.di_db.GetRKPageList<Entity.MchByBatch>(sql, where, "Id", null, query.IsPage, query.page, query.pagesize);
                return data;
            });
        }

        /// <summary>
        /// 添加机器
        /// </summary>
        /// <param name="model"></param>
        /// <param name="slots"></param>
        /// <returns></returns>
        public ResultObjModel Create(Entity.Mch model, List<Entity.Slot> slots)
        {
            return CoreStartDo.ResultAction<ResultObjModel>(result =>
            {
                var has = _tool.di_db.Get_rk_List<Mch>("select top 1 * from Mch where SN=@SN", new { model.SN }).Any();
                if (has)
                {
                    result.code = 1;
                    result.msg = $"SN已存在:{model.SN}";
                    return result;
                }
                SetCreateModel(model, false);
                if (string.IsNullOrWhiteSpace(model.BaseUserId))
                {
                    result.code = 1;
                    result.msg = $"必须指定用户";
                    return result;
                }
                model.State = MchState.可用;//默认禁用需要激活 
                Random random = new Random();
                string key = random.Next(100000, 999999).ToString();
                model.Key = key;
                model.Id = GetNoByTimeStamp.Get();
                model.MchType = model.MchMode;
                //slots.ForEach(a =>
                //{
                //    SetCreateModel(a, false);
                //    a.Id = model.Id + "-" + a.index;
                //    a.MchId = model.Id;
                //    a.SlotStateId = SlotState.可用;
                //    a.BaseUserId = model.BaseUserId;
                //});
                //如果设置了出厂日期 则自动设置报修一年
                if (model.OutTime.HasValue && model.AddMonth.HasValue)
                {

                    model.GuaranteeTime = model.OutTime.Value.AddMonths(model.AddMonth.Value);
                }
                var r = 0;
                r += _tool.di_db.do_rk_Execute(_tool.di_db.AddBySqlStr<Mch>(), model);
                //r += _tool.di_db.do_rk_Execute(_tool.di_db.AddBySqlStr<Slot>(), slots);
                if (r > 0)
                {
                    result.code = 0;
                    result.msg = "添加成功";
                    result.data = new { Id = model.Id, SN = model.SN, Key = model.Key };
                }
                else
                {
                    result.data = 1;
                    result.msg = "添加失败";
                }
                return result;
            });
        }

        public ResultModel Edit(Entity.Mch model)
        {
            return CoreStartDo.ResultAction<ResultModel>(result =>
            {

                var has = _tool.di_db.Get_rk_List<Mch>("select top 1 * from Mch where SN=@SN and Id<>@Id", new { model.SN, model.Id }).Any();
                if (has)
                {
                    result.code = 1;
                    result.msg = $"SN已存在:{model.SN}";
                    return result;
                }
                var user = _tool.di_db.Get_rk_List<User>("select top 1 from [User] where Id=@Id", new { Id = model.BaseUserId });
                if (user == null)
                {
                    result.code = 1;
                    result.msg = "用户不存在";
                    return result;
                }
                //var r = db.Mch.Where(a => a.Id == model.Id).Update(a => new Entity.Mch() { BaseUserId = model.BaseUserId, State = model.State, SN = model.SN });
                var r = _tool.di_db.do_rk_Execute("update Mch set BaseUserId=@BaseUserId,State=@State,SN=@SN where Id=@Id", new { model.BaseUserId, model.State, model.SN, model.Id });
                if (r > 0)
                {
                    result.code = 0;
                    result.msg = "success";
                }
                else
                {
                    result.code = 0;
                    result.msg = "fail";
                }
                return result;
            });
        }
        /// <summary>
        /// 获取机器列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultListModel<get_mch_pagelist_result> get_mch_pagelist(tool_get_mch_pagelist_query query)
        {
            return CoreStartDo.ResultAction<ResultListModel<get_mch_pagelist_result>>(result =>
            {
                string sql = "select c.iccid,a.*,b.Tel,b.UserName,b.Name as u_name from mch a left join [user] b on a.baseuserid = b.id  left join SimBoss_BindMch c on a.Id = c.MchID";
                string where = " where 1=1";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                //机器ID查询
                if (!string.IsNullOrWhiteSpace(query.mch_id))
                {
                    where += " and a.id like @mch_id";
                    query_dy.mch_id = $"%{query.mch_id}%";
                }
                //机器SN查询
                if (!string.IsNullOrWhiteSpace(query.mch_sn))
                {
                    where += " and a.sn like @mch_sn";
                    query_dy.mch_sn = $"%{query.mch_sn}%";
                }
                //机器名称查询
                if (!string.IsNullOrWhiteSpace(query.mch_name))
                {
                    where += " and a.Name like @mch_name";
                    query_dy.mch_name = $"%{query.mch_name}%";
                }
                //通过用户名查询
                if (!string.IsNullOrWhiteSpace(query.user_loginname))
                {
                    where += " and b.UserName=@user_loginname";
                    query_dy.user_loginname = query.user_loginname;
                }
                //通过用户姓名查询
                if (!string.IsNullOrWhiteSpace(query.user_name))
                {
                    where += " and b.Name=@user_name";
                    query_dy.user_name = query.user_name;
                }
                //通过用户电话传销
                if (!string.IsNullOrWhiteSpace(query.user_tel))
                {
                    where += " and b.Tel=@user_tel";
                    query_dy.user_tel = query.user_tel;
                }
                ResultListModel<get_mch_pagelist_result> result_pagelist = _tool.di_db.GetRKPageList<get_mch_pagelist_result>(sql, where, "a.CreateOn", query_dy, query.IsPage, query.page, query.pagesize);
                foreach (var item in result_pagelist.rows)
                {
                    if (!string.IsNullOrWhiteSpace(item.Key) && item.Key.Length > 6)
                    {
                        try
                        {
                            item.mch_info_list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Mchinfo>>(item.Key);
                        }
                        catch
                        {

                        }
                    }
                }
                return result_pagelist;
            });
        }

        /// <summary>
        ///  分配用户
        /// </summary>
        public ResultModel distribution_user(string userid, string mchid)
        {
            return CoreStartDo.ResultAction<ResultModel>(result =>
            {
                if (string.IsNullOrWhiteSpace(userid))
                {
                    result.code = 1;
                    result.msg = "必须选择用户";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(mchid))
                {
                    result.code = 1;
                    result.msg = "未选择机器";
                    return result;
                }
                var user = _tool.di_db.Get_rk_List<User>("select top 1 * from [User] where Id=@Id", new { Id = userid }).FirstOrDefault();
                if (user == null)
                {
                    result.code = 1;
                    result.msg = "所选用户不存在";
                    return result;
                }
                var mch = _tool.di_db.Get_rk_List<Mch>("select * from Mch where Id=@Mchid", new { Mchid = mchid }).FirstOrDefault();
                if (mch == null)
                {
                    result.code = 1;
                    result.msg = "所选机器不存在";
                    return result;
                }
                //直接分配机器到用户
                int updaterow = _tool.di_db.do_rk_Execute("update Mch set baseuserid=@userid where Id=@mchid", new { userid, mchid });
                if (updaterow > 0)
                {
                    string topic = $"rkt/mch/bindsuccess/";
                    string data = Newtonsoft.Json.JsonConvert.SerializeObject(new
                    {
                        sn = mch.SN
                    });
                    _rkMqtt.Publish(topic, data, MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce);
                    result.code = 0;
                    result.msg = "变更成功";

                }
                else {
                    result.code = 1;
                    result.msg = "变更失败";
                }
                return result;
            });
        }
        /// <summary>
        ///  编辑机器
        /// </summary>
        /// <returns></returns>
        public ResultObjModel NewEditMch(EditMch save_params) {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(save_params.Id))
                {
                    result.code = 1;
                    result.msg = "机器ID未入参";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(save_params.SN))
                {
                    result.code = 1;
                    result.msg = "机器SN不能为空";
                    return result;
                }
                if (!save_params.State.HasValue)
                {
                    result.code = 1;
                    result.msg = "机器状态不能为空";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(save_params.MchType))
                {
                    result.code = 1;
                    result.msg = "机器类型不能为空";
                    return result;
                }
                var mch = _tool.di_db.Get_rk_List<Mch>("select * from Mch where Id=@id", new { id = save_params.Id }).FirstOrDefault();
                if (mch == null)
                {
                    result.code = 1;
                    result.msg = "机器不存在";
                    return result;
                }
                var checksn = _tool.di_db.Get_rk_List<Mch>("select * from Mch where sn=@sn and Id<>@id", new { id = save_params.Id, sn = save_params.SN }).FirstOrDefault();
                if (checksn != null)
                {
                    result.code = 1;
                    result.msg = "机器SN已经被其他机器绑定 无法修改";
                    return result;
                }
                string old_sn = mch.SN;
                //开始变更机器基础信息
                int updaterow = _tool.di_db.do_rk_Execute("update Mch set Name=@Name,SN=@SN,MchType=@MchType,State=@State,assurance_sdt=@assurance_sdt where Id=@Id", save_params);
                if (updaterow > 0)
                {
                    result.code = 0;
                    result.msg = "保存成功";
                    result.data = $"{old_sn} to {save_params.SN}";
                }
                else {
                    result.code = 1;
                    result.msg = "保存失败";
                }
                return result;
            });
        }
        #endregion
        #region 3 物联网卡充值列表
        private string[] Serchsimreg = new string[] {
            "SimBoss_RechargeRecord.Id","SimBoss_RechargeRecord.OrderNo","SimBoss_RechargeRecord.Iccid","SimBoss_RatePlan.Name as RatePlanName","mch.Name as MchName","[user].Name as UserName","[RkOrder].O_state as PayState","[RkOrder].Pay_fee","[RkOrder].Fee_TypeId","SimBoss_RechargeRecord.SimOrder","SimBoss_RechargeRecord.SimResult","SimBoss_RechargeRecord.CreateOn,SimBoss_RechargeRecord.BaseUserId","SimBoss_RatePlan.Price as OriginalPrice"
        };
        public enum OrderState
        {
            未处理 = 0,
            待支付 = 1,
            支付成功 = 2,
            退款处理中 = 8,
            退款成功 = 16,
            退款失败 = 32
        }
        public SimListPageObjList get_simreg_list(Base_PageList_Params query)
        {
            return CoreStartDo.ResultAction<SimListPageObjList>(result =>
            {
                DateTime Sdt = DateTime.Now.AddYears(-1);
                if (!string.IsNullOrWhiteSpace(query.Sdt))
                {
                    try
                    {
                        Sdt = Convert.ToDateTime(query.Sdt);
                    }
                    catch
                    {

                    }
                }
                DateTime Edt = DateTime.Now;
                if (!string.IsNullOrWhiteSpace(query.Edt))
                {
                    try
                    {
                        Edt = Convert.ToDateTime(query.Edt);
                    }
                    catch
                    {

                    }
                }
                SimListPageObjList result_list = new SimListPageObjList();
                DateTime date_now = DateTime.Now;
                using (IDbConnection dapperconn = new SqlConnection(_tool.di_db.RkSqlConnection))
                {
                    StringBuilder sql = new StringBuilder();
                    StringBuilder sql_getRowCount = new StringBuilder();
                    sql.AppendFormat("select " + string.Join(",", Serchsimreg) + " from SimBoss_RechargeRecord left join [RkOrder] on SimBoss_RechargeRecord.OrderNo = [RkOrder].Id left join [user] on SimBoss_RechargeRecord.BaseUserId = [user].Id left join mch on SimBoss_RechargeRecord.MchId = mch.id left join SimBoss_RatePlan on SimBoss_RechargeRecord.RatePlanId = SimBoss_RatePlan.RatePlanId where 1=1 and RkOrder.O_state=2");
                    sql_getRowCount.AppendFormat("select count(SimBoss_RechargeRecord.Id) as Count,sum(pay_fee) as total_RK_price,sum(SimBoss_RatePlan.Price) as total_orgin_price from SimBoss_RechargeRecord  left join [RkOrder] on SimBoss_RechargeRecord.OrderNo = [RkOrder].Id  left join SimBoss_RatePlan on SimBoss_RechargeRecord.RatePlanId = SimBoss_RatePlan.RatePlanId  where 1=1 and RkOrder.O_state=2");
                    if (!string.IsNullOrEmpty(query.SerchKeyword))
                    {
                        sql.Append(" and (SimBoss_RechargeRecord.OrderNo like @SerchKeyword or SimBoss_RechargeRecord.Iccid like @SerchKeyword) ");
                        sql_getRowCount.Append(" and (SimBoss_RechargeRecord.OrderNo like @SerchKeyword or SimBoss_RechargeRecord.Iccid like @SerchKeyword) ");
                    }

                    sql.Append(" and  SimBoss_RechargeRecord.CreateOn >=@Sdt and  SimBoss_RechargeRecord.CreateOn <=@Edt");
                    sql_getRowCount.Append(" and  SimBoss_RechargeRecord.CreateOn >=@Sdt and  SimBoss_RechargeRecord.CreateOn <=@Edt");

                    sql.AppendFormat(" order by {0} {1}", "SimBoss_RechargeRecord.CreateOn", "desc");
                    ///如果当前设置不获取分页
                    if (query.IsPage.HasValue && !query.IsPage.Value)
                    {
                        sql.AppendFormat(" offset {0} rows", (query.pagesize * (query.page - 1)));
                        sql.AppendFormat(" fetch next {0} rows only", query.pagesize);
                    }
                    var total_info = dapperconn.Query<SimBossTotal>(sql_getRowCount.ToString(), new { SerchKeyword = query.SerchKeyword, Sdt, Edt }).SingleOrDefault();
                    var Regresult_list = dapperconn.Query<Reg_ListToAdmin>(sql.ToString(), new { SerchKeyword = query.SerchKeyword, Sdt, Edt }).ToList();
                    foreach (var item in Regresult_list)
                    {
                        item.PayState_Str = ((OrderState)item.PayState).ToString();
                        if (string.IsNullOrEmpty(item.SimResult))
                        {
                            item.SimResultMsg = "未请求到SIMBOSS";
                        }
                        else
                        {
                            try
                            {
                                JObject obj = JObject.Parse(item.SimResult.Trim());
                                item.SimResultMsg = obj["Detail"].ToString();
                            }
                            catch
                            {
                                item.SimResultMsg = "解析失败";
                            }
                        }
                    }
                    result_list.current = query.page.Value;
                    result_list.total = total_info.Count;
                    result_list.rows = result_list;
                    result_list.total_orgin_price = total_info.total_orgin_price;
                    result_list.total_RK_price = total_info.total_RK_price;
                }
                return result;
            });
        }
        #endregion
        #region 4 支付开通状态
        /// <summary>
        /// 服务商查询商户结算状态接口
        /// </summary>
        /// <param name="merchantNo"></param>
        /// <returns></returns>
        public ResultObjModel queryMerchantsSettle(string queryStartTime, string queryEndTime, string merchantNo = "", string orderStatus = "", int pageNum = 1, int pageSize = 50)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(queryStartTime) || string.IsNullOrWhiteSpace(queryEndTime))
                {
                    result.code = 1;
                    result.msg = "请选择时间";
                    return result;
                }
                queryStartTime = Convert.ToDateTime(queryStartTime).ToString("yyyy-MM-dd");
                queryEndTime = Convert.ToDateTime(queryEndTime).ToString("yyyy-MM-dd");


                if (string.IsNullOrWhiteSpace(merchantNo))
                {
                    result.code = 1;
                    result.msg = "未知的商户ID";
                    return result;
                }

                var getDes = _jdapi.queryMerchantsSettle(new queryMerchantsSettle()
                {
                    queryStartTime = queryStartTime,
                    queryEndTime = queryEndTime,
                    agentNo = _configuration["JD_Pay:agentNo"],
                    merchantNo = merchantNo,
                    orderStatus = orderStatus,
                    pageNum = pageNum,
                    pageSize = pageSize
                });
                result.code = 0;
                result.msg = "Success";
                result.data = getDes;
                return result;
            });
        }


        /// <summary>
        /// 服务商查询商户结算状态接口
        /// </summary>
        /// <param name="merchantNo"></param>
        /// <returns></returns>
        public ResultObjModel queryMerchantWXNo(string merchantNo = "")
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(merchantNo))
                {
                    result.code = 1;
                    result.msg = "未知的商户ID";
                    return result;
                }
                var getDes = _jdapi.queryMerchantWXNo(new queryMerchantWXNo()
                {

                    agentNo = _configuration["JD_Pay:agentNo"],
                    merchantNo = merchantNo
                });
                result.code = 0;
                result.msg = "Success";
                result.data = getDes;
                return result;
            });
        }
        /// <summary>
        /// 服务商查询商户结算状态接口
        /// </summary>
        /// <param name="merchantNo"></param>
        /// <returns></returns>
        public ResultObjModel querytrade(string order_id, string baseuserid)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(baseuserid))
                {
                    result.code = 1;
                    result.msg = "未知的商户ID";
                    return result;
                }
                var jd_data = _tool.di_db.Get_rk47_List<JdmerchantBase>("select * from JdmerchantBase where baseuserid =@baseuserid", new { baseuserid }).FirstOrDefault();
                if (jd_data == null)
                {
                    result.code = 1;
                    result.msg = "商户信息不存在";
                    return result;
                }
                var getDes = _jdapi.querytrade_for_rk(order_id, jd_data.merchantNo, jd_data.desKey, jd_data.mdKey);
                result.code = 0;
                result.msg = "Success";
                result.data = getDes;
                return result;
            });
        }
        /// <summary>
        /// 服务商查询商户结算状态接口
        /// </summary>
        /// <param name="merchantNo"></param>
        /// <returns></returns>
        public ResultObjModel queryrefund(string outRefundNo)
        {
            return CoreStartDo.ResultAction(result =>
            {

                var refund = _tool.di_db.Get_rk_List<Refund>(" select * from Refunds where Id=@Id", new { Id = outRefundNo }).FirstOrDefault();
                if (refund == null)
                {
                    result.code = 1;
                    result.msg = "退款订单不存在";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(refund.BaseUserId))
                {
                    result.code = 1;
                    result.msg = "未知的商户ID";
                    return result;
                }
                var jd_data = _tool.di_db.Get_rk47_List<JdmerchantBase>("select * from JdmerchantBase where baseuserid =@baseuserid", new { baseuserid = refund.BaseUserId }).FirstOrDefault();
                if (jd_data == null)
                {
                    result.code = 1;
                    result.msg = "商户信息不存在";
                    return result;
                }
                var getDes = _jdapi.queryrefund_for_rk(outRefundNo, jd_data.merchantNo, jd_data.desKey, jd_data.mdKey);
                result.code = 0;
                result.msg = "Success";
                result.data = getDes;
                return result;
            });
        }

        /// <summary>
        /// 针对7月30日订单情况进行请求验证
        /// </summary>
        /// <param name="merchantNo"></param>
        /// <returns></returns>
        public ResultObjModel start_rk_for_20200730()
        {
            return CoreStartDo.ResultAction(result =>
            {
                var ids = _tool.di_db.Get_rk_List<tempclass>("select id,Baseuserid from [order] where CreateOn>='2020-07-30 11:00:00' and O_state =1 order by CreateOn desc", null);
                _tool.di_es.Add_Log($"获取待处理数据量{ids.Count()}", "temp_20200730");
                var baseuserids = _tool.di_db.Get_rk_List<string>("select BaseUserId from [order] where CreateOn>='2020-07-30 11:00:00' and O_state =1  group by BaseUserId", null);
                _tool.di_es.Add_Log($"获取待处理数据用户量{baseuserids.Count()}", "temp_20200730");
                List<JdmerchantBase> jd_datas = _tool.di_db.Get_rk47_List<JdmerchantBase>("select baseuserid,merchantNo,mdKey,desKey from JdmerchantBase where baseuserid in @baseuserids", new { baseuserids = baseuserids.ToArray() }).ToList();
                _tool.di_es.Add_Log($"获取对应京东数据{jd_datas.Count()}", "temp_20200730");
                foreach (var item in ids)
                {
                    var jd_data = jd_datas.Where(s => s.baseuserid == item.Baseuserid).FirstOrDefault();
                    if (jd_data == null)
                    {
                        result.code = 1;
                        result.msg = "商户信息不存在";
                        return result;
                    }
                    var getDes = _jdapi.querytrade_for_rk(item.id, jd_data.merchantNo, jd_data.desKey, jd_data.mdKey);
                    _tool.di_es.Add_Log($"查询京东订单{getDes.outTradeNo}==>结论{getDes.payFinishTime}==>支付方式{getDes.piType}==>京东订单号{getDes.tradeNo}", "temp_20200730");
                    if (getDes.payStatus == "FINISH")
                    {
                        string outTradeNo = getDes.outTradeNo;//resultObj["outTradeNo"].ToString();//  
                        string JdTradeNo = getDes.tradeNo;//resultObj["tradeNo"].ToString();// 
                        string piType = getDes.piType;//resultObj["piType"].ToString();// 
                        string payFinishTime = getDes.payFinishTime;//resultObj["payFinishTime"].ToString();//  
                        string payFinishTimeFormat = payFinishTime.Insert(4, "-").Insert(7, "-").Insert(10, " ").Insert(13, ":").Insert(16, ":");
                        int p = 0;
                        if (piType.ToUpper() == "WX")
                        {
                            p = 100;
                        }
                        else if (piType.ToUpper() == "ALIPAY")
                        {
                            p = 101;
                        }
                        else if (piType.ToUpper() == "JDPAY")
                        {
                            p = 105;
                        }
                        _tool.di_db.do_rk_Execute("Update dbo.[order] set O_state=2,TradeNo=@tradeno,pay_time=@pay_time,fee_typeId=@fee_typeId where Id=@ID", new
                        {
                            Id = item.id,
                            tradeno = JdTradeNo,
                            pay_time = payFinishTimeFormat,
                            fee_typeId = p
                        });
                    }
                }
                result.code = 0;
                result.msg = "Success";
                result.data = null;
                return result;
            });
        }
        public class tempclass
        {
            public string id { get; set; }
            public string Baseuserid { get; set; }
        }

        /// <summary>
        /// 服务商查询商户结算状态接口
        /// </summary>
        /// <param name="merchantNo"></param>
        /// <returns></returns>
        public ResultObjExtModel queryApplySingle(string merchantNo)
        {
            return CoreStartDo.ResultAction<ResultObjExtModel>(result =>
            {
                if (string.IsNullOrWhiteSpace(merchantNo))
                {
                    result.code = 1;
                    result.msg = "未知的商户ID";
                    return result;
                }
                var getDes = _jdapi.queryApplySingle(new queryApplySingle()
                {
                    serialNo = _tool.di_getid.IGet_SnowFlake_Id,
                    merchantNo = merchantNo,
                });
                result.code = 0;
                result.msg = "Success";
                result.data = getDes;

                List<dataList> jd_datalist = getDes == null ? new List<dataList>() : getDes.dataList == null ? new List<dataList>() : getDes.dataList;
                var db_info = _tool.di_db.Get_rk47_List<ServiceCore.Tool.Quartz.check_aliface.OLDJdmerchantBase>("select top 1 * from JdmerchantBase where merchantNo=@merchantNo", new { merchantNo }).FirstOrDefault();
                if (db_info != null)
                {
                    string update_data = "update JdmerchantBase set {0} where merchantNo=@merchantNo";//准备执行更新语句
                    string ext_data = "";//准备拼接语句
                    foreach (var item in getDes.dataList)
                    {
                        switch (item.productNo)
                        {
                            case "401":
                                //微信
                                if (db_info.statewx != item.status)
                                {
                                    //需要更新状态
                                    ext_data += $"statewx='{item.status}',statewxmsg='{item.statusMsg}',";
                                }
                                break;
                            case "402":
                                //支付宝
                                if (db_info.statealipay != item.status)
                                {
                                    //需要更新状态
                                    ext_data += $"statealipay='{item.status}',statealipaymsg='{item.statusMsg}',";
                                }
                                break;
                            case "403":
                                //京东
                                if (db_info.statejd != item.status)
                                {
                                    //需要更新状态
                                    ext_data += $"statejd='{item.status}',statejdmsg='{item.statusMsg}',";
                                }
                                break;
                        }
                    }
                    if (!string.IsNullOrWhiteSpace(ext_data))
                    {
                        ext_data = ext_data.TrimEnd(',');
                        string t_sql = string.Format(update_data, ext_data);
                        _tool.di_db.do_rk47_Execute(t_sql, new { merchantNo });
                        //更新完了 重新再获取一下
                        db_info = _tool.di_db.Get_rk47_List<ServiceCore.Tool.Quartz.check_aliface.OLDJdmerchantBase>("select top 1 * from JdmerchantBase where merchantNo=@merchantNo", new { merchantNo }).FirstOrDefault();
                    }
                    result.Ext = new
                    {
                        db_info.merchantNo,
                        db_info.desKey,
                        db_info.mdKey,
                        wx = new
                        {
                            productid = "401",
                            state = db_info.statewx,
                            statusMsg = db_info.statewxmsg,
                            resultMsg = jd_datalist.Where(s => s.productNo == "401").Any() ? jd_datalist.Where(s => s.productNo == "401").FirstOrDefault().resultMsg : "",
                            can_re_ApplySingle = (db_info.statewx == "3" || db_info.statewx == "4") ? false : true
                        },
                        ali = new
                        {
                            productid = "402",
                            state = db_info.statealipay,
                            statusMsg = db_info.statealipaymsg,
                            resultMsg = jd_datalist.Where(s => s.productNo == "402").Any() ? jd_datalist.Where(s => s.productNo == "402").FirstOrDefault().resultMsg : "",
                            can_re_ApplySingle = (db_info.statealipay == "3" || db_info.statealipay == "4") ? false : true
                        },
                        jd = new
                        {
                            productid = "403",
                            state = db_info.statejd,
                            statusMsg = db_info.statejdmsg,
                            resultMsg = jd_datalist.Where(s => s.productNo == "403").Any() ? jd_datalist.Where(s => s.productNo == "403").FirstOrDefault().resultMsg : "",
                            can_re_ApplySingle = (db_info.statejd == "3" || db_info.statejd == "4") ? false : true
                        }
                    };
                }
                return result;
            });
        }
        /// <summary>
        /// 服务商查询商户结算状态接口
        /// </summary>
        /// <param name="merchantNo"></param>
        /// <returns></returns>
        public ResultObjModel ReApplySingle(string merchantNo, string productid, string mfee = "0.6")
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(merchantNo))
                {
                    result.code = 1;
                    result.msg = "未知的商户ID";
                    return result;
                }
                var applySingle_result = _jdapi.ApplySingle(new applySingle()
                {
                    mfeeType = "2",
                    mfee = mfee,
                    payToolId = "0",
                    productId = productid,
                    serialNo = _tool.di_getid.IGet_SnowFlake_Id,
                    agentNo = _configuration["JD_Pay:agentNo"],
                    merchantNo = merchantNo
                });
                result.code = 0;
                result.msg = "Success";
                result.data = applySingle_result;
                return result;
            });
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultObjModel search_order_model(order_search_pagelist_Params query)
        {
            return CoreStartDo.ResultAction<ResultObjModel>(result =>
            {
                if (string.IsNullOrWhiteSpace(query.TradeNo) && string.IsNullOrWhiteSpace(query.order_id))
                {
                    result.code = 0;
                    result.msg = "sucess";
                    result.data = null;
                    return result;
                }
                string sql = "select top 1 *,a.CreateOn as order_createtime from [order] a  left join [user] b on a.BaseUserId =b.Id ";
                string where = " where 1=1";
                if (!string.IsNullOrWhiteSpace(query.TradeNo))
                {
                    where += " and a.TradeNo=@TradeNo";
                }
                if (!string.IsNullOrWhiteSpace(query.order_id))
                {
                    where += " and a.Id=@order_id";
                }

                var reuslt_list = _tool.di_db.Get_rk_List<ordersearch_result>(sql + where, new { query.TradeNo, query.order_id }).FirstOrDefault();
                if (reuslt_list != null)
                {
                    reuslt_list.orderdetails = _tool.di_db.Get_rk_List<OrderDetail>("select * from OrderDetail where OrderId=@oid", new { oid = reuslt_list.OrderNo }).ToList();
                }
                result.code = 0;
                result.msg = "sucess";
                result.data = reuslt_list;
                return result;
            });
        }

        /// <summary>
        /// 服务商查询商户结算状态接口
        /// </summary>
        /// <param name="merchantNo"></param>
        /// <returns></returns>
        public ResultObjModel get_user_merchantNo(string baseuserid)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(baseuserid))
                {
                    result.code = 1;
                    result.msg = "参数不完整";
                    return result;
                }
                var get_merchantNo = _tool.di_db.Get_rk47_List<string>("select merchantNo from JdmerchantBase where baseuserid=@baseuserid", new { baseuserid });
                result.code = 0;
                result.msg = "Success";
                result.data = get_merchantNo;
                return result;
            });
        }


        public class ordersearch_result
        {
            public ordersearch_result() {
                this.orderdetails = new List<OrderDetail>();
            }
            private OrderState? classorder = null;
            private PayType? Fee_typeId_paytype = null;
            public string OrderNo { get; set; }
            public string BaseUserId { get; set; }
            public string Pay_time { get; set; }
            public decimal Total_fee { get; set; }
            public decimal Get_fee { get; set; }
            public OrderState O_State { set { classorder = value; } }
            public string O_State_str { get { return classorder.ToString(); } }
            public OrderType OrderType { get; set; }
            public PayType Fee_typeId { set { Fee_typeId_paytype = value; } }
            public string Fee_typeId_str { get { return Fee_typeId_paytype.ToString(); } }
            public string TradeNo { get; set; }
            public string TradeType { get; set; }
            public string MchName { get; set; }
            public string SN { get; set; }

            public string Details { get; set; }

            public string Tel { get; set; }
            public string UserName { get; set; }

            public string Name { get; set; }

            public string wx_name { get; set; }
            public string order_createtime { get; set; }
            public List<OrderDetail> orderdetails { get; set; }

        }
        #endregion
        /// <summary>
        ///  查询机器信息
        /// </summary>
        /// <returns></returns>
        public ResultObjModel search_mch(string keyword)
        {
            return CoreStartDo.ResultAction<ResultObjModel>(result =>
            {
                if (string.IsNullOrWhiteSpace(keyword))
                {
                    result.code = 1;
                    result.msg = "请输入搜索关键字(ID/SN)";
                    return result;
                }
                string sql = "select a.id as mchid,a.sn,a.[Key],b.iccid,c.UserName as login_name,c.Name as user_name,c.Tel from mch a " +
                                " left join SimBoss_BindMch b on a.Id = b.MchID" +
                                " left join[user] c on a.BaseUserId = c.Id ";
                string where = " where 1=1 and (a.id=@keyword or a.sn=@keyword)";
                //开始搜索相关内容
                search_mch_result result_mod = _tool.di_db.Get_rk_List<search_mch_result>(sql + where, new { keyword }).FirstOrDefault();

                result.code = 0;
                result.msg = "success";
                result.data = result_mod;
                return result;
            });
        }
        /// <summary>
        /// 搜索机器查询项
        /// </summary>
        public class search_mch_result
        {
            /// <summary>
            /// 机器SN
            /// </summary>
            public string sn { get; set; }
            /// <summary>
            /// 机器状态 
            /// </summary>
            public string mchid { get; set; }
            /// <summary>
            /// iccid
            /// </summary>
            public string iccid { get; set; }

            public string Key { get; set; }

            public List<Mchinfo> mch_info_list
            {
                get
                {
                    try
                    {
                        if (!string.IsNullOrWhiteSpace(Key) && Key.Length > 6)
                        {
                            return Newtonsoft.Json.JsonConvert.DeserializeObject<List<Mchinfo>>(this.Key);
                        }
                        else
                        {
                            return new List<Mchinfo>();
                        }
                    }
                    catch
                    {
                        return new List<Mchinfo>();
                    }
                }
            }
            /// <summary>
            ///  登录名称
            /// </summary>
            public string login_name { get; set; }
            /// <summary>
            /// 用户名称
            /// </summary>
            public string user_name { get; set; }
            /// <summary>
            /// 电话号
            /// </summary>
            public string tel { get; set; }
        }
        #region 获取京东支付转账记录
        /// <summary>
        /// 获取京东转账记录
        /// </summary>
        /// <returns></returns>
        public ResultObjExtModel get_jd_result(get_jd_result_params query)
        {
            return CoreStartDo.ResultAction<ResultObjExtModel>(result =>
            {
                if (string.IsNullOrWhiteSpace(query.month))
                {
                    query.month = DateTime.Now.ToString("yyyy-MM");
                }
                string sdt = Convert.ToDateTime($"{query.month}-01").ToString("yyyy-MM-dd");
                string edt = Convert.ToDateTime($"{query.month}-01").AddMonths(1).ToString("yyyy-MM-dd");
                string sql = "select * from Jd_Service_Model";
                string where = " where 1=1";
                if (!string.IsNullOrWhiteSpace(query.month))
                {
                    where += " and show_data>=@sdt and show_data<@edt";
                }
                if (!string.IsNullOrWhiteSpace(query.merchantNo))
                {
                    where += " and merchantNo=@merchantNo";
                }
                if (!string.IsNullOrWhiteSpace(query.orderStatus))
                {
                    where += " and orderStatus=@orderStatus";
                }
                var result_list = _tool.di_db.GetRKPageList<Jd_Service_Model>(sql, where, "show_data desc,get_fee ", new { sdt, edt, query.merchantNo, query.orderStatus }, query.IsPage, query.page, query.pagesize);
                result.code = 0;
                result.msg = "success";
                result.data = result_list;
                result.Ext = new { month = query.month, total = _tool.di_db.Get_rk_List<object>($"select  sum(pay_fee) as total_pay_fee,sum(Charge) as total_Charge,sum(get_fee) as total_get_fee,sum(cast(settlementAmount as decimal(18,2))) as total_settlementAmount from Jd_Service_Model {where}", new { sdt, edt, query.merchantNo, query.orderStatus }).FirstOrDefault() };
                return result;
            });
        }
        #endregion

        #region 京东支付改千分之6
        /// <summary>
        /// 根据商户号获取对应商户信息
        /// </summary>
        /// <returns></returns>
        public ResultObjModel get_rk_user_forJd(string merchantNo) {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(merchantNo))
                {
                    result.code = 1;
                    result.msg = "请输入商户号";
                    return result;
                }
                var jd_mod_bybaseuserid = _tool.di_db.Get_rk47_List<string>("select top 1 baseuserid from JdmerchantBase where merchantNo=@merchantNo", new { merchantNo }).FirstOrDefault();
                if (string.IsNullOrWhiteSpace(jd_mod_bybaseuserid))
                {
                    result.code = 1;
                    result.msg = "未能找到对应商户京东注册信息";
                    return result;
                }
                //返回用户信息
                var rk_user = _tool.di_db.Get_rk_List<User>("select top 1 * from [user] where Id=@id", new { id = jd_mod_bybaseuserid }).FirstOrDefault();
                if (rk_user == null)
                {
                    result.code = 1;
                    result.msg = "用户不存在";
                    return result;
                }
                result.code = 0;
                result.msg = "success";
                result.data = new
                {
                    rk_user.Id,
                    rk_user.UserName,
                    rk_user.Name,
                    rk_user.Tel,
                    rate = ((1 - rk_user.Rate) * 1000).ToString("0") + "‰"
                };
                return result;
            });
        }
        /// <summary>
        /// 修改用户到千6
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResultModel rk_user_to_q6(string id)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(id))
                {
                    result.code = 1;
                    result.msg = "商户ID必须入参";
                    return result;
                }
                //返回用户信息
                var rk_user = _tool.di_db.Get_rk_List<User>("select top 1 * from [user] where Id=@id", new { id }).FirstOrDefault();
                if (rk_user == null)
                {
                    result.code = 1;
                    result.msg = "用户不存在";
                    return result;
                }
                if (rk_user.Rate == 0.994M)
                {
                    result.code = 1;
                    result.msg = "用户当前费率已经设置为6‰";
                    return result;
                }
                int update_row = _tool.di_db.do_rk_Execute("update [user] set rate=@rate where Id=@id", new { id, rate = 0.994M });
                if (update_row > 0)
                {
                    result.code = 0;
                    result.msg = "修改成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "修改失败";
                }
                return result;
            });
        }

        #endregion

        #region 轮询整理数据
        /// <summary>
        /// 整理2020-10-12日之前机器数据
        /// </summary>
        /// <returns></returns>
        public ResultModel start_clear_run() {
            return CoreStartDo.ResultAction(result =>
            {
                Task.Factory.StartNew(() =>
                {
                    var all_mch = _tool.di_db.Get_rk_List<Mch>("select * from mch", null);
                    foreach (var item in all_mch)
                    {
                        try
                        {
                            temp_version_model newmod = new temp_version_model();
                            if (item.Key == null || item.Key.Length == 6 || item.Key == "[]")
                            {
                                //这都是不知道上报的啥玩意的

                                newmod.mchid = item.Id;
                                newmod.state = 0;
                                newmod.Temp_version_time = null;
                                newmod.remark = "unknow:未上报机器";
                            }
                            else
                            {
                                List<VersionList> version_list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<VersionList>>(item.Key);
                                if (!version_list.Where(s => s.VersionType == "T").Any())
                                {
                                    newmod.mchid = item.Id;
                                    newmod.state = 5; //无需处理
                                    newmod.Temp_version_time = null;
                                    newmod.remark = "常温机";
                                }
                                else
                                {
                                    newmod.mchid = item.Id;
                                    newmod.state = 0; //无需处理
                                    newmod.Temp_version_time = Convert.ToDateTime(version_list.Where(s => s.VersionType == "T").FirstOrDefault().UpdateTime);
                                    newmod.BoardTime = Convert.ToDateTime(version_list.Where(s => s.VersionType == "T").FirstOrDefault().BoardTime);
                                    newmod.remark = "温控";
                                }
                            }
                            _tool.di_db.do_rk_Execute(_tool.di_db.AddBySqlStr<temp_version_model>(), newmod);
                        }
                        catch (Exception ex)
                        {

                        }
                    }

                });
                result.code = 0;
                result.msg = "success";
                return result;
            });
        }

        /// <summary>
        /// 获取带温度信息的机器
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultListModel<search_version_model> get_temp_list(search_temp_info query)
        {
            return CoreStartDo.ResultAction<ResultListModel<search_version_model>>(result =>
            {
                string sql = "select DATALENGTH(b.SN) as sn_length,a.*,b.SN,b.Name as mchname,b.BaseUserId,b.[key],c.UserName,c.Id,c.Name,c.Tel,b.ConnUpdateOn " +
                            " from temp_version_model a " +
                            " left " +
                            "  join mch b on a.mchid = b.id " +
                            " left " +
                            "  join [user] c on b.BaseUserId = c.Id ";
                string where = " where (mchid like '%WP%' or DATALENGTH(b.SN)= 40) and b.BaseUserId != 'RK_test' and b.SN is not null ";
                //" order by a.temp_version_time desc, b.ConnUpdateOn desc";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                if (query.state.HasValue)
                {
                    where += " and a.state=@state";
                    query_dy.state = query.state.Value;
                }
                if (!string.IsNullOrWhiteSpace(query.designated_uid))
                {
                    where += " and a.designated_uid=@designated_uid";
                    query_dy.designated_uid = query.designated_uid;
                }
                if (!string.IsNullOrWhiteSpace(query.start_time))
                {
                    where += " and a.last_update_time>=@start_time";
                    query_dy.start_time = query.start_time;
                }
                if (!string.IsNullOrWhiteSpace(query.end_time))
                {
                    where += " and a.last_update_time<=@end_time";
                    query_dy.end_time = query.end_time;
                }

                if (query.mch_type.HasValue)
                {
                    switch (query.mch_type.Value)
                    {
                        case 0:
                            where += " and a.remark='温控'";
                            break;
                        case 1:
                            where += " and a.remark='常温机'";
                            break;
                        case 2:
                            where += " and a.remark='unknow:未上报机器'";
                            break;
                    }
                }
                if (!string.IsNullOrWhiteSpace(query.SerchKeyword))
                {
                    where += " and (b.SN like @SerchKeyword or b.Name like @SerchKeyword or c.username like @SerchKeyword or c.Tel like @SerchKeyword)";
                    query_dy.SerchKeyword = $"%{query.SerchKeyword}%";
                }
                if (_tool.di_user.USER.role_id == "1282601877913092096" || _tool.di_user.USER.uid == "4")
                {
                    //运营要看的
                }
                else if (_tool.di_user.USER.role_id != "SuperAdmin" && _tool.di_user.USER.role_id != "Finance_Manager")
                {
                    //where += " and a.state <> '1'";
                    where += " and a.designated_uid=@designated_uid";
                    query_dy.designated_uid = _tool.di_user.USER.uid;
                }
                else
                {
                    where += " and a.state <> '1'";
                    where += " and a.designated_uid is null";
                }
                return _tool.di_db.GetRKPageList<search_version_model>(sql, where, "a.last_update_time", query_dy, query.IsPage, query.page, query.pagesize);
            });
        }
        /// <summary>
        /// 标记处理完成
        /// </summary>
        /// <param name="mchid"></param>
        /// <returns></returns>
        public ResultModel end_temp(string mchid)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(mchid))
                {
                    result.code = 1;
                    result.msg = "机器ID未入参";
                    return result;
                }
                var temp_model = _tool.di_db.Get_rk_List<temp_version_model>("select top 1 * from temp_version_model where mchid=@mchid", new { mchid }).FirstOrDefault();
                if (temp_model == null)
                {
                    result.code = 1;
                    result.msg = "待标记数据已处理";
                    return result;
                }
                else if (temp_model.state != 0)
                {
                    result.code = 1;
                    result.msg = "当前机器无需处理";
                    if (temp_model.state == 1 && !string.IsNullOrWhiteSpace(temp_model.uname))
                    {
                        result.code = 1;
                        result.msg = $"当前机器 {temp_model.uname} 已标记完成";
                    }
                    return result;
                }
                else if (temp_model.designated_uid != _tool.di_user.USER.uid)
                {
                    result.code = 1;
                    result.msg = "当前机器未分配到您处理"; 
                    return result;
                }
                else
                {
                    int rows = _tool.di_db.do_rk_Execute("update temp_version_model set uid=@uid,uname=@uname,end_time=@end_time,state=@state where mchid=@mchid and state='0'", new
                    {
                        uid = _tool.di_user.USER.uid,
                        uname = _tool.di_user.USER.u_name,
                        end_time = DateTime.Now,
                        state = 1,
                        mchid = mchid
                    });
                    if (rows > 0)
                    {
                        result.code = 0;
                        result.msg = "处理成功";
                        return result;
                    }
                    else
                    {
                        result.code = 1;
                        result.msg = "处理失败";
                        return result;
                    }
                }
            });
        }


        /// <summary>
        /// 改变处理状态
        /// </summary>
        /// <param name="mchid"></param>
        /// <returns></returns>
        public ResultModel change_state(string mchid,string diy_remark,int state)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(mchid))
                {
                    result.code = 1;
                    result.msg = "机器ID未入参";
                    return result;
                }
                var temp_model = _tool.di_db.Get_rk_List<temp_version_model>("select top 1 * from temp_version_model where mchid=@mchid", new { mchid }).FirstOrDefault();
                if (temp_model == null)
                {
                    result.code = 1;
                    result.msg = "待标记数据已处理";
                    return result;
                }
                else if (temp_model.state == 1 && !string.IsNullOrWhiteSpace(temp_model.uname))
                {
                    result.code = 1;
                    result.msg = $"当前机器 {temp_model.uname} 已标记完成";
                    return result;
                }
                else if (temp_model.designated_uid != _tool.di_user.USER.uid)
                {
                    result.code = 1;
                    result.msg = "当前机器未分配到您处理";
                    return result;
                }
                else
                {
                    string uid = "";
                    string uname = "";
                    DateTime? end_time = null;
                    if (state == 1)
                    {
                        uid = _tool.di_user.USER.uid;
                        uname = _tool.di_user.USER.u_name;
                        end_time = DateTime.Now;
                    }
                    int rows = _tool.di_db.do_rk_Execute("update temp_version_model set uid=@uid,uname=@uname,end_time=@end_time,last_update_time=@last_update_time,state=@state,diy_remark=@diy_remark where mchid=@mchid", new
                    {
                        last_update_time = DateTime.Now,
                        state = state,
                        mchid = mchid,
                        diy_remark = diy_remark,
                        end_time,
                        uname,
                        uid
                    }); 
                    if (rows > 0)
                    {
                        result.code = 0;
                        result.msg = "处理成功";
                        return result;
                    }
                    else
                    {
                        result.code = 1;
                        result.msg = "处理失败";
                        return result;
                    }
                }
            });
        }


        /// <summary>
        /// 指定人
        /// </summary>
        /// <returns></returns>
        public ResultModel designated_person(designated_person_params Params)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(Params.uid))
                {
                    result.code = 1;
                    result.msg = "必须指定处理人";
                    return result;
                }
                if (Params.mchids == null || !Params.mchids.Any())
                {
                    result.code = 1;
                    result.msg = "必须指定待处理机器";
                    return result;
                }
                rk_user u_mod = _tool.di_db.GetList<rk_user>("select top 1 * from rk_user where uid=@uid", new { uid = Params.uid }).FirstOrDefault();
                if (u_mod == null)
                {
                    result.code = 1;
                    result.msg = "指定人不存在";
                    return result;
                }
                if (_tool.di_user.USER.role_id != "SuperAdmin" && _tool.di_user.USER.role_id != "Finance_Manager")
                {
                    result.code = 1;
                    result.msg = "权限不足 无法分配";
                    return result;
                }
                if (_tool.di_user.USER.uid != "4") //权限狗不需要验证
                {
                    List<temp_version_model> temp_mch_list = _tool.di_db.Get_rk_List<temp_version_model>("select * from temp_version_model where mchid in @mchids", new { mchids = Params.mchids }).ToList();
                    if (temp_mch_list.Where(s => s.state != 0).Any())
                    {
                        result.code = 1;
                        result.msg = $"机器ID{string.Join(',', temp_mch_list.Where(s => s.state != 0).Select(s => s.mchid))}状态无需处理";
                        return result;
                    }
                }
                //if (temp_mch_list.Where(s => s.state == 0 && !string.IsNullOrWhiteSpace(s.designated_uid)).Any())
                //{
                //    result.code = 1;
                //    result.msg = $"机器ID{string.Join(',', temp_mch_list.Where(s => s.state == 0 && !string.IsNullOrWhiteSpace(s.designated_uid)).Select(s => s.mchid))}已分配处理人 无需重复处理";
                //    return result;
                //}
                int rows = _tool.di_db.do_rk_Execute("update temp_version_model set designated_uid=@designated_uid,designated_uname=@designated_uname,designated_time=@designated_time where mchid in @mchids", new
                {
                    designated_uid = u_mod.uid,
                    designated_uname = u_mod.u_name,
                    designated_time = DateTime.Now,
                    mchids = Params.mchids
                });
                if (rows > 0)
                {
                    result.code = 0;
                    result.msg = "分配成功";
                    result.data = rows;
                }
                else
                {
                    result.code = 1;
                    result.msg = "分配失败 DB ERROR";
                }
                return result;
            });
        }
        #endregion
    }
}
